<script setup lang="ts">
import { computed, ref, inject } from 'vue'
import { type Component } from "@/models/component";
import { getComponent } from "@/core/componentMapper";
import * as cpUtils from './utils';
import Error from "./Error.vue";
import * as injectKeys from "@/services/injectKeys";

const datasetServices = inject(injectKeys.datasetKey)!
const sqlAnalyzeServices = inject(injectKeys.sqlAnalyzeKey)!
const dbServices = inject(injectKeys.dbKey)!


const props = defineProps<{ component: Component }>()
const model = props.component

const cp = getComponent(props.component.tag)

// TODO:
const visible = computed(() => {
    if (model.visible === undefined) {
        return true
    }

    if (typeof model.visible !== 'boolean') {
        const sqlinfo = model.visible as {
            sql: string
        }
        const tables = sqlAnalyzeServices.getTableNames(sqlinfo.sql)
        const data = cpUtils.getReactData(model.id, sqlinfo.sql, tables, {
            dataset: datasetServices,
            sqlAnalyze: sqlAnalyzeServices,
            db: dbServices,
        })

        if (data.value.rows.length === 0) {
            return false
        }

        const firstValue = data.value.rows[0][data.value.fields[0]]
        return firstValue
    }

    return model.visible as boolean

})

let styles = model.styles

if (model.gridArea) {
    styles = {
        ...styles,
        gridArea: model.gridArea
    }
}

</script>

<template>
    <Error v-if="visible">
        <component :style="styles" :id="props.component.id" :data-cp-tag="props.component.tag" :data-debug-tag="props.component.debugTag" :is="cp"
            :model="props.component">
        </component>

    </Error>
</template>

<style scoped></style>